package com.ibeetl.eval;

import java.util.List;
import java.util.Map;

import org.jdom2.Element;
/**
 * 保存计算的所有中间结果
 * @author xiandafu
 *
 */
public class EvalContext {
	private TreeNode parent = null;
	private TreeNode node = null;
	EvalEngine evalEngine = null;
	Map<String,Object> initPara = null;
	public  EvalContext(EvalEngine evalEngine,Map<String,Object> paras){
		this.evalEngine = evalEngine;
		this.initPara = paras;
	}
	//集合节点，进入之前
	public TreeNode enter(String parentName,Element parentRef){
		
		TreeNode  child = new TreeNode();
		child.setNodeName(parentName);
		child.setNodeRefInfo(parentRef);
		if(parent==null){
			this.parent = child;
			this.parent.setParas(initPara);
		}else{
			parent.getChildren().add(child);
			List<TreeNode>  children = parent.getChildren();
			if(children.size()==1){
				child.setParas(parent.getParas());
			}else{
				TreeNode lastOne = children.get(children.size()-1);
				child.setParas(lastOne.getParas());
			}
			child.setParentNode(this.parent);
			
			this.parent = child;
			
		}
		return parent;
	}
	
	public TreeNode goNext(String name,Element ref){
		TreeNode  next = new TreeNode();
		next.setNodeName(name);
		next.setNodeRefInfo(ref);
		next.setParentNode(parent);
		parent.getChildren().add(next);
		//保留调用的参数,来自于上一个节点或者父亲节点（如果是老大节点)
		if(node!=null){
			next.setParas(node.getParas());
		}else{
			next.setParas(parent.getParas());
		}
		node = next;
		return next;
	}
	
	

	/**
	 * 本节点执行上下文参数根据上一个的来，还是所有已经执行过的节点，目前
	 * 简单处理是根据上一个的来。
	 * @return
	 */
	public Map<String,Object> prepareNext(){
		if(node==null){
			return evalEngine.newMap(parent.getParas());
		}else{
			return evalEngine.merage(node.getParas(), node.getNodeName(), node.getResult());

		}
	}
	

	
	public void exist(){
		this.parent = parent.parentNode;
		this.node = null;
	}
	public EvalEngine getEvalEngine() {
		return evalEngine;
	}
	public void setEvalEngine(EvalEngine evalEngine) {
		this.evalEngine = evalEngine;
	}
	
	
	
}
